package com.pl.spring.security.oauth2.server.configure;

import com.pl.spring.security.oauth2.server.domain.TbPermission;
import com.pl.spring.security.oauth2.server.domain.TbUser;
import com.pl.spring.security.oauth2.server.service.TbPermissionService;
import com.pl.spring.security.oauth2.server.service.imp.TbUserServiceImpl;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: pl
 * @Date: 2020/1/8 20:43
 * @Description:
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private TbUserServiceImpl tbUserService;
    @Autowired
    private TbPermissionService tbPermissionService;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        TbUser user = tbUserService.getUserByUserName(s);
        ArrayList<GrantedAuthority> grantedAuthorities = Lists.newArrayList();
        if (user!=null){
            List<TbPermission> tbPermissions = tbPermissionService.selectByUserId(user.getId());
            tbPermissions.forEach(tbPermission -> {
                SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(tbPermission.getEnname());
                grantedAuthorities.add(grantedAuthority);
            });
            System.out.println("+++++++++++++++++++++++++++++++");
            return new User(user.getUsername(),user.getPassword(),grantedAuthorities);
        }

        return null;
    }
}